<template>
  <div class="recycle">
    <div class="search-header">
      <div class="recycle-header">
        <span>回收站</span>
        <span> 删除内容计入回收站，将在30天后彻底清除，请及时管理</span>
      </div>
      <div class="search" v-if="query.bin_type == 2">
        <el-input
          style="width: 200px"
          v-model="query.keyword"
          placeholder="搜索..."
        />
        <div class="sort-icons">
          <el-popover
            ref="popover"
            placement="left"
            :width="80"
            trigger="click"
          >
            <div
              class="btns"
              style="
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                gap: 4px;
              "
            >
              <el-button
                style="
                  margin: 0 !important;
                  border: none !important;
                  width: 100%;
                "
                class="sort-item"
                v-for="(item, index) in sortList"
                :key="index"
                :class="{
                  active: currentId == item.id,
                }"
                :type="currentId == item.id ? 'primary' : 'default'"
                @click="toggoleSort(item)"
              >
                {{ item.label }}
              </el-button>
            </div>
            <template #reference>
              <el-icon v-if="down" style="cursor: pointer; font-size: 24px">
                <Desc />
              </el-icon>
              <el-icon v-else style="cursor: pointer; font-size: 24px">
                <Asc />
              </el-icon>
            </template>
          </el-popover>
          <el-icon
            v-if="isCard"
            @click="isCard = !isCard"
            style="cursor: pointer; font-size: 24px"
          >
            <Menu />
          </el-icon>
          <el-icon
            v-else
            @click="isCard = !isCard"
            style="cursor: pointer; font-size: 24px"
          >
            <Toggle />
          </el-icon>
        </div>
      </div>
    </div>
    <div class="tabs-wrapper" v-loading="loading">
      <div style="flex: 1">
        <el-tabs
          v-model="query.bin_type"
          class="demo-tabs"
          @tab-change="handleClick"
        >
          <!-- 笔记  -->
          <el-tab-pane label="笔记" :name="2">
            <div class="padding-10 note-box" ref="noteBoxRef">
              <el-row
                :gutter="20"
                v-if="noteList.length && isCard"
                class="item-box"
              >
                <el-popover
                  :teleported="false"
                  placement="right"
                  :width="80"
                  trigger="contextmenu"
                  class="custom-popover"
                  v-for="(item, c) in noteList"
                  :key="item.id"
                  :ref="
                    (ref) => {
                      mapRef(ref, item.id)
                    }
                  "
                >
                  <template #reference>
                    <el-card
                      @contextmenu="handleMenu(item.id)"
                      style="
                        width: 180px;
                        border: none !important;
                        height: 248px;
                        border: none !important;
                        cursor: pointer;
                      "
                      shadow="hover"
                    >
                      <template #header>
                        <div class="header-btn" style="display: flex">
                          <!-- <div style="text-align: end"></div> -->
                          <el-text line-clamp="1">{{ item.title }}</el-text>
                        </div>
                      </template>
                      <!-- replaceImg(item.content, '160', '120') -->
                      <el-text
                        v-if="item.content && item.icon == 'Document'"
                        :innerHTML="item.content"
                        line-clamp="5"
                        style="width: 160px; height: 110px"
                      >
                      </el-text>
                      <div
                        style="
                          width: 160px;
                          height: 110px;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                        "
                        v-else-if="item.icon == 'FlowChart'"
                      >
                        <el-icon style="font-size: 44px" color="#409eff">
                          <FlowChart />
                        </el-icon>
                      </div>
                      <div
                        style="
                          width: 160px;
                          height: 110px;
                          display: flex;
                          align-items: center;
                          justify-content: center;
                        "
                        v-else-if="item.icon == 'Xmind'"
                      >
                        <el-icon style="font-size: 44px" color="#409eff">
                          <Xmind />
                        </el-icon>
                      </div>
                      <div
                        v-else
                        style="
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          height: 110px;
                          cursor: pointer;
                        "
                      >
                        <el-icon :size="56" color="#409efe"
                          ><Document
                        /></el-icon>
                      </div>
                      <div class="tags" style="height: 60px">
                        <el-space
                          wrap
                          class="tag-wrapper"
                          v-if="item.label && item.label.length"
                        >
                          <el-text
                            type="primary"
                            line-clamp="2"
                            style="width: fit-content"
                          >
                            <el-tag
                              round
                              v-for="(tag, i) in item.label"
                              :key="i"
                              type="primary"
                              size="small"
                              style="margin: 0 2px 0 0; padding: 2px 6px"
                              >{{ tag.label_name }}</el-tag
                            ></el-text
                          >
                        </el-space>
                      </div>
                      <template #footer>
                        {{
                          item.updated_at &&
                          new Date(item.updated_at).toLocaleDateString()
                        }}
                      </template>
                    </el-card>
                  </template>
                  <div
                    class="btns-wrapper"
                    style="display: flex; flex-direction: column"
                  >
                    <el-button
                      v-for="(button, n) in moreFilledbuttons"
                      :key="n"
                      style="
                        margin: 0 !important;
                        border: none !important;
                        justify-content: flex-start;
                      "
                      @click="handleRecoverOrDelete(button, item)"
                    >
                      {{ button.label }}
                    </el-button>
                  </div>
                </el-popover>
              </el-row>
              <!-- <List :list="noteList" v-if="!isCard"></List> -->
              <div class="list" v-if="!isCard">
                <div
                  style="width: 100%; height: 100px"
                  shadow="hover"
                  v-for="(item, index) in noteList"
                  :key="index"
                  class="card-item"
                  @contextmenu="handleClickListItem($event, item)"
                >
                  <div
                    style="
                      width: 40px;
                      height: 100%;
                      flex-shrink: 0;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                    "
                  >
                    <el-icon color="#409efe" :size="24" v-if="item.icon">
                      <Component :is="MapComponent[item.icon]" />
                    </el-icon>
                    <el-icon v-else :size="24" color="#409efe"
                      ><Document
                    /></el-icon>
                  </div>
                  <div
                    style="
                      width: calc(100% - 40px - 120px);
                      display: flex;
                      flex-direction: column;
                      justify-content: space-between;
                      height: 100%;
                    "
                  >
                    <el-text truncated style="width: 100%; height: 20px">
                      {{ item.title }}
                    </el-text>
                    <el-text
                      v-if="item.content && item.icon == 'Document'"
                      line-clamp="2"
                      style="width: 100%; height: calc(100% - 30px)"
                      :innerHTML="item.content.replace(/<img\b[^>]*>/gi, '')"
                    >
                    </el-text>
                  </div>
                  <div
                    style="
                      width: 120px;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      flex-shrink: 0;
                      height: 100%;
                    "
                  >
                    {{ new Date(item.updated_at).toLocaleDateString() }}
                  </div>

                  <div
                    v-if="itemId === item.id"
                    class="operationMenu"
                    style="display: flex; flex-direction: column"
                    v-click-outside="handleClickOutside"
                  >
                    <el-button
                      v-for="(button, n) in moreFilledbuttons"
                      :key="n"
                      style="
                        margin: 0 !important;
                        border: none !important;
                        justify-content: flex-start;
                      "
                      @click="handleRecoverOrDelete(button, item)"
                    >
                      {{ button.label }}
                    </el-button>
                  </div>
                </div>
              </div>
              <el-empty
                description="暂无数据"
                v-if="!loading && !noteList.length"
              />
              <pagination
                :total="noteListTotal"
                v-model:page="query.page"
                v-model:limit="query.limit"
                @pagination="getList"
              />
            </div>
          </el-tab-pane>
          <!-- 文件夹 -->
          <el-tab-pane
            label="文件夹"
            :name="1"
            style="
              display: flex;
              flex-direction: column;
              justify-content: space-between;
            "
            class="note-box"
          >
            <div
              class="folder"
              style="
                padding: 10px;
                display: flex;
                align-items: center;
                gap: 4px;
                flex-wrap: wrap;
              "
            >
              <el-popover
                :teleported="false"
                placement="right"
                :width="80"
                trigger="contextmenu"
                class="custom-popover"
                v-for="(item, c) in noteList"
                :key="item.id"
                :ref="
                  (ref) => {
                    folderMapRef(ref, item.id)
                  }
                "
              >
                <template #reference>
                  <el-card
                    style="width: 180px"
                    shadow="hover"
                    @contextmenu="handleMenuFolder(item.id)"
                    @click="showDeleteFolder(item)"
                  >
                    <div
                      class="folder"
                      style="
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        gap: 4px;
                      "
                    >
                      <el-icon color="#f8b83f" size="24"
                        ><FolderOpened
                      /></el-icon>
                      <el-text line-clamp="1"> {{ item.title }}</el-text>
                    </div>
                  </el-card>
                </template>
                <div
                  class="btns-wrapper"
                  style="display: flex; flex-direction: column"
                >
                  <el-button
                    v-for="(button, n) in moreFilledbuttons"
                    :key="n"
                    style="
                      margin: 0 !important;
                      border: none !important;
                      justify-content: flex-start;
                    "
                    @click="handleRecoverOrDelete(button, item)"
                  >
                    {{ button.label }}
                  </el-button>
                </div>
              </el-popover>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div style="height: 100px" v-if="noteListTotal">
        <pagination
          :total="noteListTotal"
          v-model:page="query.page"
          v-model:limit="query.limit"
          @pagination="getList"
        />
      </div>
    </div>
  </div>
  <el-dialog
    style="padding: 0; border-radius: 15px"
    :show-close="false"
    v-model="deleteFolderVisible"
    width="500"
    class="delete-note-folder"
  >
    <template #header>
      <div class="p-10" style="font-weight: 500">回收站-{{ folderName }}</div>
    </template>
    <div class="folder-item-wrapper p-10" v-if="folderList.length">
      <div v-for="item in folderList" :key="item.id" class="flex-between">
        <div class="title">
          <el-icon color="#409efe" v-if="item.icon" :size="24">
            <Component :is="MapComponent[item.icon]"></Component>
          </el-icon>
          <el-icon color="#409efe" v-else :size="24"><Document /></el-icon>
          <el-text line-clamp="1"> {{ item.name_title }}</el-text>
        </div>
        <div class="content">
          <el-text line-clamp="1">
            {{
              item.updated_at && new Date(item.updated_at).toLocaleDateString()
            }}
          </el-text>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer p-10">
        <el-button type="primary" @click="recoveryFolder">全部恢复</el-button>
        <el-button type="danger" @click="deleteFolder"> 永久删除 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue'
import {
  httpGetRecycleList,
  httpRevertNoteOrFolder,
  httpGetRecyleFolders,
  httpDeleteNoteForever,
} from '@/api/note.js'
import Pagination from '@/components/pagination/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Desc from '@/icons/Desc.vue'
import Asc from '@/icons/Asc.vue'
import Menu from '@/icons/Menu.vue'
import Toggle from '@/icons/Toggle.vue'
// import List from './components/List.vue'
import useNote from '@/hooks/useNote'
import useNoteStore from '@/stores/note'
import { ClickOutside as vClickOutside } from 'element-plus'
import { useViewPort } from '@/hooks/useView.js'
const noteState = useNoteStore()
import { storeToRefs } from 'pinia'
const { FlowChart, Xmind, MapComponent } = useNote()
const folderName = ref('新建文件夹')
const deleteFolderVisible = ref(false)
const loading = ref(false)
const noteList = ref([])
const noteListTotal = ref()
const selectSortItem = ref()
const query = reactive({
  sort_order: 1,
  page: 1,
  keyword: '',
  limit: 20,
  bin_type: 2,
})
const sortList = ref([
  {
    id: 1,
    label: '创建时间',
  },
  {
    id: 2,
    label: '更新时间',
  },
  {
    id: 3,
    label: '笔记名称',
  },
])
const down = ref(true)
const isCard = ref(true)
const currentId = ref(2)

const moreFilledbuttons = ref([
  {
    id: '1',
    label: '恢复',
  },
  {
    id: '2',
    label: '彻底删除',
  },
])
const folderList = ref([])

const mapaa = ref({})
const mapRef = (ref, index) => {
  mapaa.value[index] = ref
}
const handleMenu = (item) => {
  Object.keys(mapaa.value).forEach((key) => {
    if (key != item && mapaa.value[key]) {
      mapaa.value[key].hide()
    }
  })
}
const folderMap = ref({})
const folderMapRef = (ref, index) => {
  folderMap.value[index] = ref
}
const handleMenuFolder = (item) => {
  Object.keys(folderMap.value).forEach((key) => {
    if (key != item && folderMap.value[key]) {
      folderMap.value[key].hide()
    }
  })
}
const selectedFolder = ref({})
const showDeleteFolder = async (item) => {
  deleteFolderVisible.value = true
  selectedFolder.value = item
  const res = await httpGetRecyleFolders({
    recycle_bin_folder_id: item.id,
  })
  if (res.list.length) {
    folderList.value = res.list
  }
}
//全部恢复
const recoveryFolder = () => {
  revertNoteOrFolder(selectedFolder.value)
  deleteFolderVisible.value = false
}
const deleteFolder = (item) => {
  ElMessageBox.confirm(
    '永久删除的文件无法恢复，请谨慎操作',
    '确定要彻底删除吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteFolderVisible.value = false
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {})
}

const handleRecoverOrDelete = async (btn, item) => {
  //   彻底删除
  if (btn.id == '2') {
    ElMessageBox.confirm(
      '永久删除的文件无法恢复，请谨慎操作',
      '确定要彻底删除吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(async () => {
        const res = await httpDeleteNoteForever({
          recycle_id: item.id,
        })
        if (res) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'danger',
          message: '删除失败',
        })
      })
  } else {
    revertNoteOrFolder(item)
  }
}
const revertNoteOrFolder = async (item) => {
  const res = await httpRevertNoteOrFolder({
    fd_id: item.id,
    restore_type: query.bin_type,
  })
  if (res) {
    ElMessage.success({
      type: 'success',
      message: '恢复成功',
    })
    getList()
    noteState.getFolderListData()
  } else {
    ElMessage.error({
      type: 'error',
      message: '恢复失败',
    })
  }
}
const handleClick = (tab, event) => {
  noteList.value = []
  getList()
}
const mapSortFn = {
  1: () => {
    query.sort_order = down.value ? 1 : 3
  },
  2: () => {
    query.sort_order = down.value ? 1 : 4
  },
  3: () => {
    query.sort_order = down.value ? 2 : 5
  },
}
const toggoleSort = (item) => {
  if (currentId.value == item.id) {
    down.value = !down.value
  } else {
    currentId.value = item.id
    down.value = true
  }
  mapSortFn[item.id]()
  getList()
  selectSortItem.value = item
}
const getList = async (showLoading = true) => {
  if (showLoading) loading.value = true
  const response = await httpGetRecycleList({
    ...query,
  }).catch(() => null)
  if (showLoading) loading.value = false
  if (!response) return
  const { list, total } = response
  noteList.value = list
  noteListTotal.value = total
}
getList()

const itemId = ref('')
const { vw, vh } = useViewPort()
const handleClickOutside = (item) => {
  itemId.value = undefined
  noteBoxRef.value.style.overflow = 'auto'
}
const noteBoxRef = ref(null)
const handleClickListItem = (e, item) => {
  e.preventDefault()
  e.stopPropagation()
  itemId.value = item.id
  let posY = e.clientY
  let posX = e.clientX
  nextTick(() => {
    let domWidth = document.querySelector('.operationMenu').offsetWidth
    let domHeight = document.querySelector('.operationMenu').offsetHeight
    noteBoxRef.value.style.overflow = 'hidden'
    if (posX > vw.value - domWidth) {
      posX -= domWidth
    }
    if (posY > vh.value - domHeight) {
      posY = vh.value - domHeight
    }
    document
      .querySelector('.operationMenu')
      .setAttribute('style', `top:${posY}px;left:${posX}px;z-index:99`)
  })
}
</script>
<style>
.delete-note-folder {
  .el-dialog__header {
    padding-bottom: 0 !important;
  }
}
</style>
<style scoped lang="scss">
.p-10 {
  padding: 10px;
}
.recycle {
  height: 100vh;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-header {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  .recycle-header {
    flex: 1;
    display: flex;
    gap: 4px;
    & :nth-child(1) {
      font-size: 18px;
      font-weight: 600;
    }
    & :last-child {
      font-size: 12px;
      margin-top: 4px;
      color: #aaaaaa;
    }
  }
  .search {
    flex: 1;
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    flex-direction: column;
    gap: 4px;
    position: relative;
    .sort-icons {
      display: flex;
      gap: 4px;
      cursor: pointer;
      position: absolute;
      bottom: -30px;
      z-index: 1;
    }
  }
}
.tabs-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}
.folder-item-wrapper {
  border: 1px solid #ccc;
  height: 260px;
  overflow-y: auto;
}
.note-box {
  height: calc(100vh - 140px);
  overflow: auto;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .item-box {
    padding-left: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    :deep(.el-card__header) {
      padding: 10px !important;
      border: none !important;
    }
    :deep(.el-card__body) {
      padding: 0 10px !important;
      border: none !important;
    }
    :deep(.el-card__footer) {
      padding: 0 10px !important;
      border: none !important;
      text-align: end;
    }
  }
}
/* 滚动条样式 */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/* 滑块样式 */
::-webkit-scrollbar-thumb {
  background-color: #9f9f9f;
  border-radius: 10px;
}
/* 滚动条轨道样式 */
::-webkit-scrollbar-track {
  background-color: #fcfcfc;
  border-radius: 10px;
}

.list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  cursor: pointer;
}

.card-item {
  --el-card-border-color: var(--el-border-color-light);
  --el-card-border-radius: 4px;
  --el-card-padding: 20px;
  --el-card-bg-color: var(--el-fill-color-blank);
  background-color: var(--el-card-bg-color);
  border: 1px solid var(--el-card-border-color);
  border-radius: var(--el-card-border-radius);
  color: var(--el-text-color-primary);
  overflow: hidden;
  transition: var(--el-transition-duration);
  padding: 10px;
  display: flex;
  align-items: center;
  &:hover {
    box-shadow: var(--el-box-shadow-light);
  }
}
.operationMenu {
  font-size: 14px;
  position: fixed;
  z-index: 9;
  background-color: #fff;
  border-radius: 5px;
  display: flex;
  padding: 10px;
  flex-direction: column;
  box-shadow: var(--el-box-shadow-light);
}
</style>
